//
//  PlaylistManager.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/12.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import CoreData

private let entityName = CoreDataEntityName.playlist.rawValue
private let context = CoreDataHelper.getContext()

extension Playlist {
  func getAudioCount() -> Int {
    if let audioIDs = (self.audioIDs?.components(separatedBy: ",").filter {$0.count > 0 }) {
      return audioIDs.count
    } else {
      return 0
    }
  }
  
  func getAudios() -> [Audio]? {
    if let audioIDs = (self.audioIDs?.components(separatedBy: ",").filter {$0.count > 0 }),
      audioIDs.count > 0 {
      
      let ids = audioIDs.map { Int($0)! }
      
      var audios = [Audio]()
      ids.forEach {
        if let audio = EntityManager.fetch(Audio.self, fetchType: .id($0))?.first {
          audios.append(audio)
        }
      }
      return audios
    } else {
      return nil
    }
  }
  
  func appendUnique(audioIDs: String) throws {
    var currentIDsArray = self.audioIDs?.components(separatedBy: ",").filter {$0.count > 0 }
    if currentIDsArray == nil { currentIDsArray = [String]() }
    let appendIDsArray = audioIDs.components(separatedBy: ",").filter {$0.count > 0 }
    appendIDsArray.forEach {
      if !currentIDsArray!.contains($0) {
        currentIDsArray!.append($0)
      }
    }
    self.audioIDs = currentIDsArray!.joined(separator: ",")
    do {
      try context.save()
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  func update(audios: [Audio]?) throws {
    if let audios = audios {
      audioIDs = audios.map { "\($0.id)" }.joined(separator: ",")
    } else {
      audioIDs = nil
    }
    
    do {
      try context.save()
    } catch let error {
      loggingPrint("Update playlist audios failed. \(error.localizedDescription)")
      throw error
    }
  }
}

extension Playlist {
  static func getAll() -> [Playlist]? {
    let request = NSFetchRequest<Playlist>()
    let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
    request.entity = entity
    request.predicate = NSPredicate(format: "userID = %@", "\(UserManager.shared.currentUser!.identifier)")
    request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
    do {
      let playlists = try context.fetch(request)
      return playlists
    } catch let error {
      loggingPrint(error)
      return nil
    }
  }
  
  static func createPlaylist(name: String, audioIDs: String) throws {
    let playlist = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! Playlist
    playlist.id = NSUUID().uuidString
    playlist.name = name
    playlist.audioIDs = audioIDs
    playlist.createdAt = Date()
    if let currentUser = UserManager.shared.currentUser {
      playlist.userID = Int16(currentUser.identifier)
    }
    
    do {
      try context.save()
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  static func remove(playlist: Playlist) throws {
    context.delete(playlist)
    do {
      try context.save()
    } catch let error {
      loggingPrint(error)
      throw error
    }
  }
  
  static func remove(id: Int) throws {
    if let playlist = EntityManager.fetch(Playlist.self, fetchType: .id(id))?.first {
      context.delete(playlist)
      do {
        try context.save()
      } catch let error {
        loggingPrint(error)
        throw error
      }
    }
  }
}
